import os
import uuid

from flask import render_template, jsonify, request, session, redirect, url_for, current_app

from models import db
from models.index import User, Follow, Collection, Category, News
from utils.qiniu import upload_qiniu
from views import user_blu, index


@user_blu.route("/center")
def user_center():
    user_id = session.get("user_id")
    if not user_id:
        redirect(url_for("index_blu.index"))

    user = db.session.query(User).filter(User.id == user_id).first()

    return render_template("index/user.html", user=user)


@user_blu.route("/user_base_info")
def user_base_info():
    return render_template("index/user_base_info.html")


# 设置签名昵称和性别
@user_blu.route("/basic", methods=["POST", "GET"])
def user_basic():
    # 获取数据
    signature = request.json.get("signature")
    nick_name = request.json.get("nick_name")
    gender = request.json.get("gender")

    # 获取用户id
    user_id = session.get("user_id")

    try:
        # 数据库修改
        user = db.session.query(User).filter(User.id == user_id).first()
        if not user:
            ret = {
                "errno": "4002",
                "errmsg": "？？？？？？？？"
            }
            return jsonify(ret)

    except Exception as e:
        print(e)
        ret = {
            "errno": "4003",
            "errmsg": "？？？网络错误？？？？？"
        }
        return jsonify(ret)

    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender

    db.session.commit()

    ret = {'errno': "0", "errmsg": "设置成功"}
    return jsonify(ret)


# 修改密码 页面
@user_blu.route("/user_pass_info", methods=["POST", "GET"])
def user_pass_info():
    re_type = request.method

    if re_type == "GET":
        return render_template("index/user_pass_info.html")

    #
    # else:
    #     '''post'''
    #     pass


# 修改密码
@user_blu.route("/password", methods=["POST", "GET"])
def user_password():
    # 获取数据
    new_password = request.json.get("new_password")
    old_password = request.json.get("old_password")
    # 用户id
    user_id = session.get("user_id")

    # 数据库查询
    try:
        user = db.session.query(User).filter(User.id == user_id, User.password_hash == old_password).first()

        if not user:
            ret = {
                "errno": "1001",
                "errmsg": "?????"
            }

            return jsonify(ret)

    except Exception as e:
        print(e)
        ret = {
            "errno": "4001",
            "errmsg": "????错误"
        }

        return jsonify(ret)

    user.password_hash = new_password

    db.session.commit()

    ret = {
        "errno": "0",
        "errmsg": "okokok"
    }

    return jsonify(ret)


# 设置头像 页面
@user_blu.route("/user_pic_info")
def user_user_pic_info():
    user_id = session.get("user_id")

    user = db.session.query(User).filter(User.id == user_id).first()
    return render_template("index/user_pic_info.html", user=user)


# 设置头像
@user_blu.route("/avatar", methods=["POST", "GET"])
def user_avatar():
    user_id = session.get("user_id")
    # 获取图片数据
    image = request.files.get("avatar")

    if not image:
        ret = {
            "errno": "0001",
            "errmsg": "设置失败"
        }
        return jsonify(ret)

    # 获取文件的后缀名
    image_type = image.filename[image.filename.rfind("."):]

    # 图片名字加密 省略

    # 图片名字
    image_filename = "_xjzx_" + str(uuid.uuid3(uuid.NAMESPACE_URL, image.filename)) + image_type

    # # 图片在静态文件夹中的路径
    # image_path = os.path.join('/static/upload/user_head_image', image_file)
    #
    # # 图片的绝对路径
    # upload_path = os.path.join(current_app.root_path, 'static/upload/user_head_image', image_file)
    #
    #
    # # 保存图片到硬盘
    # image.save(upload_path)
    # 存到七牛云
    ret = upload_qiniu(image, image_filename)

    print(ret)  # http://qhq9d7bnb.hn-bkt.clouddn.com/weitezh_图片名  把这个路径存到数据库

    user = db.session.query(User).filter(User.id == user_id).first()

    # 保存到数据库
    user.avatar_url = ret

    db.session.commit()

    ret = {
        "errno": "0"
        , "errmsg": "设置成功",
        "avatar_url": ret
    }

    return jsonify(ret)


# 显示关注
@user_blu.route("/user_follow")
def user_follow_show():
    # 分页参数
    page_size = 2  # 没页四个
    page_index = 1  # 查询的是第几页开始

    page = request.args.get("page")

    page = int(page) if page else page_index

    # 获取用户的关注的用户列表
    user_id = session.get("user_id")

    # users = db.session.query(Follow).filter(Follow.followed_id==user_id).all()
    # 通过paginate方法分页
    pagination = db.session.query(Follow).filter(Follow.followed_id == user_id).paginate(int(page), int(page_size),
                                                                                         False)

    object_list = pagination.items

    print(object_list)  # [<Follow 1, 2>, <Follow 1, 3>, <Follow 1, 4>, <Follow 1, 5>]

    # print(users) # [<Follow 1, 2>, <Follow 1, 3>, <Follow 1, 4>, <Follow 1, 5>, <Follow 1, 7>]

    # 被关注的人的id列表
    en_users_id = [i.follower_id for i in object_list]

    # 被关注人的对象列表
    en_users = [db.session.query(User).filter(User.id == i).first() for i in en_users_id]

    return render_template("index/user_follow.html", en_users=en_users, pagination=pagination)


# 取消关注
@user_blu.route("/follow", methods=["POST", "GET"])
def user_follow():
    # 获取参数
    # 关注的人的id
    follow_id = request.json.get("user_id")

    print(follow_id)
    # 当前用户的id
    user_id = session.get("user_id")

    if not user_id:
        return redirect('/login')

    try:
        user = db.session.query(Follow).filter(Follow.followed_id == user_id, Follow.follower_id == follow_id).first()

        print(user)
        if user:
            # 数据库删除数据
            db.session.delete(user)
            db.session.commit()

            ret = {"errno": "0",
                   "errmsg": "取消成功"}
        else:
            ret = {"errno": "1002",
                   "errmsg": "网络错误"}
    except Exception as e:
        ret = {"errno": "1001",
               "errmsg": "网络错误"}
        print(e)

    return jsonify(ret)


# 新闻列表页面
@user_blu.route("/user_news_list")
def user_user_new_list():
    user_id = session.get("user_id")

    # 查询请求页码
    page = int(request.args.get('page', 1))
    # 查询当前用户的所有新闻

    news_paginate = db.session.query(News).filter(News.user_id == user_id).paginate(page, 8, False)

    return render_template("index/user_news_list.html", news_paginate=news_paginate)


# 新闻发布_显示页面
@user_blu.route("/user_news_release")
def user_news_release():
    # 新闻分类列表
    new_rele_list = db.session.query(Category).filter(Category.id != 1).all()

    return render_template("index/user_news_release.html", new_rele_list=new_rele_list)


# 新闻发布_发布功能
@user_blu.route("/release", methods=["POST"])
def user_release():
    # 判断登录

    # 获取数据
    title = request.form.get("title")
    category = request.form.get("category")
    digest = request.form.get("digest")
    content = request.form.get("content")
    image = request.files.get("index_image")

    news = News()

    news.title = title
    news.category_id = category
    news.source = "个人发布"
    news.digest = digest
    news.content = content
    news.user_id = session.get("user_id")
    news.status = 1  # 1代表 正在审核

    print(category)
    print(category)
    if image:
        # 获取文件的后缀名
        image_type = image.filename[image.filename.rfind("."):]

        # 图片名字加密 省略

        # 图片名字
        image_filename = "_xjzx_" + str(uuid.uuid3(uuid.NAMESPACE_URL, image.filename)) + image_type

        # 将这个图片上传到七牛云
        qiniu_image_url = upload_qiniu(image, image_filename)

        news.index_image_url = qiniu_image_url

    db.session.add(news)
    db.session.commit()

    ret = {
        "errno": "0",
        "errmsg": "发布成功"
    }

    return jsonify(ret)


# 新闻收藏
@user_blu.route("/user_collection")
def user_collection():
    #
    user_id = session.get("user_id")
    # 查询当前用户
    user = db.session.query(User).filter(User.id == user_id).first()
    # 查询用户收藏的文章
    collection_news = user.collection_news
    return render_template("index/user_collection.html", collection_news=collection_news)


# 点击收藏和取消收藏
@user_blu.route("/news/collect", methods=["POST"])
def news_collect():
    # 获取当前登录用户
    user_id = session.get("user_id")
    if not user_id:
        ret = {"errno": "5002",
               "errmsg": "请先登录"}
        return jsonify(ret)

    # 获取请求参数
    action = request.json.get("action")
    news_id = request.json.get("news_id")

    if action == "do":
        mret = Collection(user_id=user_id, news_id=news_id)
        db.session.add(mret)
        db.session.commit()
        ret = {
            "errno": "0",
            "errmsg": "收藏成功"
        }

    elif action == "undo":
        mret = db.session.query(Collection).filter(Collection.news_id == news_id, Collection.user_id == user_id).first()
        if mret:

            db.session.delete(mret)
            db.session.commit()
            ret = {
                "errno": "0",
                "errmsg": "取消收藏成功"
            }
        else:
            ret = {
                "errno": "013232",
                "errmsg": "网络错误"
            }
    else:
        ret = {
            "errno": "013232",
            "errmsg": "网络错误"
        }

    return jsonify(ret)


"""""||=|==================================================================|=||
||=|==================================================================|=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                      啥也不是                      |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||=|                                                                  |=||
||====================================================================|=||
||====================================================================|=||"""""
